package manager;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.DBConnector;
import utils.LockUtil;

/**
 * Servlet implementation class RemoveSessionFromCourse
 */
public class RemoveSessionFromCourse extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
       
    
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		if (!request.getSession(false).getAttribute("type").equals("admin")) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Only Admin can remove sessions");
			return;			
		}
		
		String courseName = request.getParameter("course_name");
		
		if (courseName == null) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Missing Course Name parameter");
			return;
		}
		
		DBConnector dbConn = null;
		try {
			synchronized (LockUtil.getCourseSessionLock()) {
				dbConn = new DBConnector();
				PreparedStatement stmnt = dbConn.getConnection().prepareStatement(
							"DELETE from course_sessions " +
							"where course_name = ? AND " + 
							"session_day = ? AND session_start_time = ? AND session_end_time = ?");
							
							
				stmnt.setString(1, courseName);
				String[] names = request.getParameterValues("check");
				if (names == null){
					response.sendRedirect("course_details.jsp?course_name=" + courseName);
					return;
				}
				
				for (String name : names){
					String[] sessionDetails = name.split(",");
					if (sessionDetails.length != 3) {
						response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
						return;					
					}
					
					stmnt.setInt(2, Integer.parseInt(sessionDetails[0]));
					stmnt.setInt(3, Integer.parseInt(sessionDetails[1]));
					stmnt.setInt(4, Integer.parseInt(sessionDetails[2]));
					stmnt.execute();
				}
		}
			
			
			response.sendRedirect("course_details.jsp?course_name=" + courseName);
		
		} catch (SQLException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
